package com.lzy.system.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.cacheAnno.RedisCache;
import com.lzy.cacheAnno.RedisCacheDel;
import com.lzy.exception.BusException;
import com.lzy.system.organization.dto.SysConfigAddDTO;
import com.lzy.system.organization.dto.convert.SysConfigConvert;
import com.lzy.system.organization.entity.SysConfig;
import com.lzy.system.organization.mapper.SysConfigMapper;
import com.lzy.system.organization.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

/**
 * <p>
 * 系统设置 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2023-12-09
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {

    private SysConfigConvert sysConfigConvert;

    @Autowired
    public SysConfigServiceImpl(SysConfigConvert sysConfigConvert) {
        this.sysConfigConvert = sysConfigConvert;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @RedisCacheDel(key = "sysConfig")
    public void saveSysConfig(SysConfigAddDTO sysConfigAddDTO) throws BusException {
        SysConfig sysConfig = sysConfigConvert.addDtoToEntity(sysConfigAddDTO);
        SysConfig data = getOne(new QueryWrapper() {{
            last("limit 1");
        }},true);
        if(data == null){
            data = sysConfig;
            boolean save = save(data);
            if(!save){
                throw new BusException("保存失败");
            }
        }else{
            data.setConfig(sysConfig.getConfig());
            boolean save = updateById(data);
            if(!save){
                throw new BusException("修改失败");
            }
        }

    }

    @Override
    @RedisCache(key = "sysConfig")
    public Map getJson() throws BusException {
        SysConfig data = this.getOne(new QueryWrapper() {{
            last("limit 1");
        }},true);
        Yaml yaml = new Yaml();
        Map config_map = (Map) yaml.load(data.getConfig());
        return config_map;
    }
}
